'''多个权限，权限可以访问的接口地址、模块文件记录在对应的权限下'''


class Scope:
    allow_api = []  # 支持接口名称层次的权限
    allow_module = []  # 支持红图（py模块）层次的权限
    forbidden = []  # 支持指定接口排除，不让使用

    def __add__(self, other):
        # 运算符重载 可以失效对象的相加
        self.allow_api = self.allow_api + other.allow_api
        self.allow_api = list(set(self.allow_api))  # 集合可以去重，不允许有重复的元素
        self.allow_module = self.allow_module + other.allow_module
        self.allow_module = list(set(self.allow_module))
        self.forbidden = self.forbidden + other.forbidden
        self.forbidden = list(set(self.forbidden))
        return self  # 返回一个对象，使self.add() 还能再次调用 self.add().add()


class AdminScope(Scope):
    # allow_api = ['v1.super_user+get_user', 'v1.super_user+delete_user']
    allow_module = ['v1.user','v1.case','v1.tool','v1.apis','v1.mock']

    def __init__(self):
        pass
        # self+UserScope()


class UserScope(Scope):
    forbidden = ['v1.user+super_get_user', 'v1.user+super_delete_user']

    # allow_api = ['v1.user+get_user', 'v1.user+delete_user']
    def __init__(self):
        self + AdminScope()


def is_in_scope(scope, endpoint):
    # scope 传进来是一个字符串’UserScope‘，不是一个对象
    # 反射 通过globals()把字符串’UserScope‘转为类UserScope
    # 现在的 endpoint 是 v1.super_get_user  是request.endpoint的值
    # 修改后的 endpoint 是 v1.user +super_get_user  v1.红图名称+接口名称
    scope = globals()[scope]()
    splits = endpoint.split('+')
    red_name = splits[0]
    print(endpoint)
    if endpoint in scope.forbidden:  # 如果有指定不让访问的接口，就直接停止
        return False
    if endpoint in scope.allow_api:
        return True
    if red_name in scope.allow_module:
        return True
    return False


'''普通用户
eyJhbGciOiJIUzUxMiIsImlhdCI6MTYzMjgwMDI4MywiZXhwIjoxNjM1MzkyMjgzfQ.eyJ1aWQiOjIsInR5cGUiOjEwMCwic2NvcGUiOiJVc2VyU2NvcGUifQ.SieOcbUWw4goSHmfTSxRY8ywL6xc42Y1zWHAikp1DaEkVrP_FtKIdEyGJLCJ6Wfqfim1sYxWE925b1VpmSomEg
'''

'''管理员
eyJhbGciOiJIUzUxMiIsImlhdCI6MTYzMjgwMDE2NywiZXhwIjoxNjM1MzkyMTY3fQ.eyJ1aWQiOjMsInR5cGUiOjEwMCwic2NvcGUiOiJBZG1pblNjb3BlIn0.zdNlaHK6MML34U2tajb3rIh51UAEcmU45RAVEmCnSV3qygYsnFMrsXE_1t3SD2m0CES2o_-urb8FDPdDjRzILQ
'''
